package com.party.admin.biz.system;

import com.google.common.base.Strings;
import com.party.admin.biz.wechat.WechatBizService;
import com.party.admin.biz.wechat.WechatTokenBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.system.BindMerchantInput;
import com.party.admin.web.dto.input.wechat.GetTicketResponse;
import com.party.admin.web.dto.input.wechat.TokenResponse;
import com.party.common.constant.Constant;
import com.party.core.exception.BusinessException;
import com.party.core.model.WechatPayCode;
import com.party.core.model.member.MemberExternalApp;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.MemberMerchant;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.member.IMemberExternalAppService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberMerchantService;
import com.party.core.service.wechat.IWechatAccountService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *用户商户信息实体接口服务
 * Created by wei.li
 *
 * @date 2017/5/19 0019
 * @time 11:42
 */
@Service
public class MemberMerchantBizService {

    @Autowired
    private IMemberMerchantService memberMerchantService;

    @Autowired
    private IWechatAccountService wechatAccountService;

    @Autowired
    private WechatBizService wechatBizService;

    @Autowired
    private WechatTokenBizService wechatTokenBizService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private IMemberExternalAppService memberExternalAppService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 保存商户信息
     * @param memberMerchant 商户信息
     * @throws Exception 异常信息
     */
    @Transactional
    public void save(MemberMerchant memberMerchant) throws Exception{

       /* memberMerchant.setOfficialAccountName(trim(memberMerchant.getOfficialAccountName()));
        memberMerchant.setOfficialAccountId(trim(memberMerchant.getOfficialAccountId()));
        memberMerchant.setOfficialAccountSecret(trim(memberMerchant.getOfficialAccountSecret()));
        memberMerchant.setMerchantName(trim(memberMerchant.getMerchantName()));
        memberMerchant.setMerchantId(trim(memberMerchant.getMerchantId()));
        memberMerchant.setMerchantApiKey(trim(memberMerchant.getMerchantApiKey()));

        if (StringUtils.isNotEmpty(memberMerchant.getId())) {
            MemberMerchant t = memberMerchantService.get(memberMerchant.getId());

            // 将编辑表单中的非NULL值覆盖数据库记录中的值
            MyBeanUtils.copyBeanNotNull2Bean(memberMerchant, t);
            memberMerchantService.update(t);

            if (WechatPayCode.DEPLOY_TYPE_FILL.equals(memberMerchant.getDeployType())){

                // 初始化商户信息
                WechatAccount wechatAccount
                        = wechatAccountService.findByMemberId(memberMerchant.getMemberId());
                if (null == wechatAccount){
                    this.inserWechatAccount(memberMerchant);
                }
                else {
                    this.updateWechatAccount(wechatAccount, memberMerchant);
                }
            }

        } else {
            String memberId = RealmUtils.getCurrentUser().getId();
            memberMerchant.setCreateBy(memberId);
            memberMerchant.setUpdateBy(memberId);
            memberMerchantService.insert(memberMerchant);

            if (WechatPayCode.DEPLOY_TYPE_FILL.equals(memberMerchant.getDeployType())){

                // 初始化商户信息
                this.inserWechatAccount(memberMerchant);
            }

        }*/
    }


    /**
     * 绑定商户信息
     *
     * @param input 输入参数
     */
    public void bindMerchant(BindMerchantInput input){
        MemberGroup member = memberGroupService.get(input.getMemberId());
        member.setOpenStatus(input.getOpenStatus());
        member.setMandatoryAttention(input.getMandatoryAttention());
        member.setDeployType(input.getDeployType());
        memberGroupService.update(member);

        MemberExternalApp memberExternalApp
                = memberExternalAppService.getSet(input.getMemberId(), input.getDeployType());
        memberExternalApp.setExternalAccountId(input.getExternalAccountId());
        memberExternalApp.setExternalMerchantId(input.getExternalMerchantId());
        memberExternalAppService.update(memberExternalApp);
    }


    /**
     * 保存商户信息
     *
     * @param wechatOpenMember 微信开放平台
     * @throws Exception 异常信息
     */
    @Transactional
    public AjaxResult save(WechatOpenMember wechatOpenMember)throws Exception{
        AjaxResult ajaxResult = new AjaxResult(true);
        if (Constant.DEPLOY_TYPE_FILL.equals(wechatOpenMember.getDeployType())){
            wechatOpenMember.setAuthorizerAppid(trim(wechatOpenMember.getAuthorizerAppid()));
            wechatOpenMember.setSecret(trim(wechatOpenMember.getSecret()));
            if (Strings.isNullOrEmpty(wechatOpenMember.getId())){
                // 插入前先验证该appid是否存在
                WechatOpenMember old = wechatOpenMemberService.findByAppidAndDeployType(wechatOpenMember.getAuthorizerAppid(),
                        wechatOpenMember.getDeployType());
                if (null != old && wechatOpenMember.getAuthorizerAppid().equals(old.getAuthorizerAppid())) {
                    ajaxResult.setSuccess(false);
                    ajaxResult.setDescription("保存微信账号信息失败, appID : {0} 的填写授权已经存在".replace("{0}",
                            old.getAuthorizerAppid()));
                    return ajaxResult;
                }
                wechatOpenMember.setType(Constant.WECHAT_ACCOUNT_TYPE_PARTNER);
                wechatOpenMemberService.insert(wechatOpenMember);
            }
            else {
                wechatOpenMemberService.update(wechatOpenMember);
            }
            this.updateTokenAndTicket(wechatOpenMember);
            return ajaxResult;
        } else {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("保存微信账号信息失败");
            return ajaxResult;
        }
    }

    /**
     * 去后缀
     * @param property 参数
     * @return 参数
     */
    public String trim(String property) {
        if (StringUtils.isNotEmpty(property)) {
            return property.replace(" ", "");
        }
        return property;
    }





    public void updateTokenAndTicket(WechatOpenMember wechatOpenMember){

        TokenResponse tokenResponse = wechatTokenBizService.getTokenResponse(wechatOpenMember.getAuthorizerAppid(),
                wechatOpenMember.getSecret());
        if (com.party.common.utils.StringUtils.isEmpty(tokenResponse.getAccess_token())) {
            // 各种错误的判定
            String errcode = tokenResponse.getErrcode();
            if ("40013".equals(errcode)) {
                codeDescription(WechatPayCode.INVALID_APP_ID, "公众号id错误, 请仔细检查微信公众号");
            } else if ("40125".equals(errcode)) {
                codeDescription(WechatPayCode.INVALID_APP_SECRET, "公众号secret错误, 请仔细检查微信公众号");
            } else if ("40164".equals(errcode)) {
                codeDescription(WechatPayCode.INVALID_IP, "未添加到ip白名单, 请将同行者ip添加到微信公众号ip白名单");
            }
        }
        String token = tokenResponse.getAccess_token();
        if (!Strings.isNullOrEmpty(token)){
            wechatOpenMember.setAuthorizerAccessToken(token);
            try {
                GetTicketResponse response = wechatBizService.getTicket(token);
                if (null != response && !Strings.isNullOrEmpty(response.getTicket())){
                    wechatOpenMember.setTicket(response.getTicket());
                }
            } catch (Exception e) {
                logger.error("获取ticket异常", e);
            }
            String type = wechatOpenMember.getType();
            if (StringUtils.isNotEmpty(type) && Constant.WECHAT_ACCOUNT_TYPE_SYSTEM.equals(type)) {

            } else {
                wechatOpenMember.setType(Constant.WECHAT_ACCOUNT_TYPE_PARTNER);
            }
            wechatOpenMemberService.update(wechatOpenMember);
        }
        else {
            throw new BusinessException("生成token异常");
        }
    }

    private void codeDescription(Integer code, String description) {
        throw new BusinessException("Code: " + code + " " + description);
    }
}
